<?php

namespace Hilaoyu\LaravelExtend\Services\Menus\Controllers;

use Hilaoyu\LaravelExtend\ControllerBase;
use Hilaoyu\LaravelExtend\Supports\AuthorizeCheck;
use Hilaoyu\Utils\UtilStr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Str;

class MenusController extends ControllerBase
{

    public function menus(Request $request){
        $menu_key = (string)$request->route('menu_key','');
        $menus = config('menus.'.trim($menu_key),[]);
        $menus = $this->check($menus);
        comResponse()->success()->with($menus);
        return $this->renderingResponse();
    }


    protected function check($menus){ //authorizationCheck
        if(!is_array($menus)){
            return $menus;
        }
        foreach($menus as $menu_key => &$menu){
            $authorization = data_get($menu,'authorization','');
            $route_name = data_get($menu,'route_name','');
            $route_params = (array)data_get($menu,'route_params',[]);

            if($authorization){
                $ability = Str::before($authorization,':');
                $authorization_args = explode(',',Str::after($authorization,':'));

                /*if($route_name == 'web.console.competitions'){
                    dd($ability,$authorization_args);
                }*/

                if(!Gate::check($ability,$authorization_args)){
                    unset($menus[$menu_key]);
                    continue;
                }
            }


            if($route_name){

                if(!AuthorizeCheck::CheckRoute($route_name)){
                    unset($menus[$menu_key]);
                    continue;
                }

                //dump( $menu,$has_authority);

                data_set($menu,'href',route($route_name,$route_params));
            }

            $children = data_get($menu,'children',[]);
            unset($menu['children']);

            if(!empty($children)){
                 $children = $this->check($children);
                 if(!empty($children)){
                     $menu['children'] = $children;
                 }
            }
        }
        return $menus;
    }



}
